// MainActivity.kt
package com.example.thirdhomework

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

const val FIRST_MSG = "FIRST_MSG"

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化 editText
        editText = findViewById(R.id.editText)

        // 初始化 first 按钮
        val first: Button = findViewById(R.id.first)
        first.setOnClickListener {
            val intent = Intent(this, MainActivity2::class.java)
            intent.putExtra(FIRST_MSG, editText.text.toString())
            startActivity(intent)
        }

        // 第二个按钮，启动第三个 Activity,在第三个 Activity 中输入内容确定后可将内容返回到MainActivity并显示返回结果
        val second: Button = findViewById(R.id.second)
        second.setOnClickListener {
            val intent = Intent(this, MainActivity3::class.java)
            startActivityForResult(intent, 0)
        }

        // 第四个按钮，启动第四个 Activity
        val fourth: Button = findViewById(R.id.fourth)
        fourth.setOnClickListener {
            val intent = Intent(this, MainActivity4::class.java)
            startActivity(intent)
        }

        // 第五个按钮，启动第五个 Activity
        val fifth: Button = findViewById(R.id.fifth)
        fifth.setOnClickListener {
            val intent = Intent(this, MainActivity5::class.java)
            startActivity(intent)
        }
    }

    //重载 onActivityResult 方法，获取返回的数据并显示
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (resultCode == 1) {
                val textView: TextView = findViewById(R.id.textView)
                textView.text = data?.getStringExtra(SECOND_MSG)
            }
        }
    }
}